<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>WebGPU自适应渲染引擎 Danseat</title>
    <script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/renderers/webgpu/WebGPURenderer.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/loaders/GLTFLoader.js"></script>
    <style>
        body { margin: 0; overflow: hidden; }
        #perfPanel {
            position: absolute; padding: 10px;
            background: rgba(0,0,0,0.7); color: #0f0;
            font-family: monospace; z-index: 100;
        }
    </style>
</head>
<body>
    <div id="perfPanel">GPU:检测中... | FPS:0 | 画质:自动</div>
    <script>
        // ================= 1. 五级硬件适配引擎 =================
        const gpuTier = {
            tier1: ['nvidia', 'amd', 'apple'],  // 高端独显（AMD、NVIDIA、苹果）
            tier2: ['intel iris', 'm1', 'm2'], // 高性能核显（M1、M2等）
            tier3: ['intel uhd', 'radeon vega'], // 普通核显
            tier4: ['nvidia 10', 'nvidia 9', 'amd r9'] // 老式独显
        };

        // 硬件检测与画质策略
        async function detectGPUTier() {
            const gl = document.createElement('canvas').getContext('webgpu');
            if (!gl) return 'tier5'; // 完全不支持WebGPU
            
            const adapter = await navigator.gpu.requestAdapter();
            const info = adapter.info;
            const gpuName = (info.gpu || '').toLowerCase();
            
            if (gpuTier.tier1.some(vendor => gpuName.includes(vendor))) 
                return 'tier1';
            if (gpuTier.tier2.some(vendor => gpuName.includes(vendor))) 
                return 'tier2';
            if (gpuTier.tier3.some(vendor => gpuName.includes(vendor))) 
                return 'tier3';
            if (gpuTier.tier4.some(vendor => gpuName.includes(vendor))) 
                return 'tier4';
            
            return 'tier5'; // 最低兼容模式
        }

        // ================= 2. 自适应渲染管线 =================
        async function initRenderer() {
            const tier = await detectGPUTier();
            let renderer, qualitySettings;
            
            switch(tier) {
                case 'tier1': // 高端显卡：启用完整WebGPU+光线追踪
                    renderer = new THREE.WebGPURenderer({ 
                        antialias: true, 
                        powerPreference: "high-performance"
                    });
                    qualitySettings = { 
                        resolution: 1.0, 
                        shadows: 'pcf-soft', 
                        textures: '8k',
                        rayTracing: true
                    };
                    break;
                    
                case 'tier2': // 高性能核显：WebGPU基础功能
                    renderer = new THREE.WebGPURenderer();
                    qualitySettings = { 
                        resolution: 0.8, 
                        shadows: 'pcf', 
                        textures: '4k' 
                    };
                    break;
                    
                case 'tier3': // 普通核显：混合渲染模式
                    try {
                        renderer = new THREE.WebGPURenderer();
                    } catch {
                        renderer = new THREE.WebGLRenderer();
                    }
                    qualitySettings = { 
                        resolution: 0.6, 
                        shadows: 'basic', 
                        textures: '2k' 
                    };
                    break;
                    
                default: // 老显卡/兼容模式：降级到WebGL
                    renderer = new THREE.WebGLRenderer({ 
                        antialias: true,
                        powerPreference: "low-power" 
                    });
                    qualitySettings = { 
                        resolution: 0.5, 
                        shadows: 'none', 
                        textures: '1k',
                        instancing: true // 启用实例化减少DrawCall
                    };
            }
            
            renderer.setPixelRatio(window.devicePixelRatio * qualitySettings.resolution);
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);
            return { renderer, qualitySettings, tier };
        }

        // ================= 3. 智能资源加载系统 =================
        function createTextureLoader(quality) {
            const maxSize = quality.textures === '8k' ? 8192 : 
                           quality.textures === '4k' ? 4096 : 
                           quality.textures === '2k' ? 2048 : 1024;
            
            return new THREE.TextureLoader().setOptions({ 
                anisotropy: maxSize > 2048 ? 16 : 8 
            });
        }

        // ================= 4. 核心渲染引擎 =================
        async function initEngine() {
            const { renderer, qualitySettings, tier } = await initRenderer();
            const scene = new THREE.Scene();
            const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
            camera.position.z = 5;
            
            // 动态LOD系统（根据硬件自动分级）
            const lodSystem = {
                levels: [
                    { distance: 50, detail: 0.2 }, // 远距离低模
                    { distance: 20, detail: 0.5 }, // 中距离中模
                    { distance: 0, detail: 1.0 }   // 近距离高模
                ],
                update: (object) => {
                    const dist = camera.position.distanceTo(object.position);
                    const level = lodSystem.levels.find(l => dist >= l.distance);
                    object.traverse(child => {
                        if (child.isMesh) {
                            child.geometry = level.detail < 0.5 ? 
                                child.userData.lowPoly : 
                                child.userData.highPoly;
                        }
                    });
                }
            };
            
            // 模型加载（含多级LOD）
            const loader = new THREE.GLTFLoader();
            const model = await loader.loadAsync('model.glb');
            model.scene.traverse(child => {
                if (child.isMesh) {
                    // 生成低多边形版本
                    child.userData.highPoly = child.geometry;
                    child.userData.lowPoly = new THREE.SimplifyModifier()
                        .modify(child.geometry, Math.floor(child.geometry.attributes.position.count * 0.3));
                }
            });
            scene.add(model.scene);
            
            // ================= 5. 渲染循环优化 =================
            let clock = new THREE.Clock();
            function animate() {
                requestAnimationFrame(animate);
                
                // 动态负载均衡（低端设备跳过物理计算）
                const delta = clock.getDelta();
                if (tier !== 'tier4' && tier !== 'tier5' || delta < 0.03) {
                    model.scene.rotation.x += 0.01;
                    lodSystem.update(model.scene);
                }
                
                renderer.render(scene, camera);
                updatePerfPanel(renderer, tier);
            }
            animate();
            
            // 性能监控
            function updatePerfPanel(renderer, tier) {
                const fps = Math.round(1 / clock.getDelta());
                const gpuName = renderer.getContext().adapter?.info.gpu || '兼容模式';
                document.getElementById('perfPanel').innerHTML = 
                    `GPU: ${gpuName} | FPS:${fps} | 画质:${qualitySettings.textures}`;
            }
        }
        
        // 启动引擎
        initEngine();
    </script>
</body>
</html>